package goft

import (
	"github.com/gin-gonic/gin"
	"reflect"
)

var Responderlist []Responder

func init() {
	Responderlist = []Responder{new(StringResponder), new(ModelResponder)}
}

func Convert(a interface{}) gin.HandlerFunc {
	ref_type := reflect.TypeOf(a)
	ref_value := reflect.ValueOf(a)
	for _, v := range Responderlist {
		rvalue := reflect.ValueOf(v).Elem()
		if rvalue.Type().ConvertibleTo(ref_type) {
			rvalue.Set(ref_value)
			return rvalue.Interface().(Responder).RespondTo()
		}
	}
	return nil
}

type Responder interface {
	RespondTo() gin.HandlerFunc
}

type StringResponder func(*gin.Context) string

func (this StringResponder) RespondTo() gin.HandlerFunc {
	return func(context *gin.Context) {
		context.JSON(200, this(context))
	}
}

type ModelResponder func(ctx *gin.Context) Model

func (this ModelResponder) RespondTo() gin.HandlerFunc {
	return func(context *gin.Context) {
		context.JSON(200, this(context).String())
	}
}
